package com.lanou.bbs.controller;

import com.lanou.bbs.dao.UserDao;
import com.lanou.bbs.entity.User;
import com.lanou.bbs.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserDao userDao;
    @Autowired
    private UserServiceImpl userService;


    @ResponseBody
    @RequestMapping("/findById")
    public User findById(int uid) {
        return userService.findById(uid);
    }

    @RequestMapping("/login")
    @ResponseBody
    public boolean login(User user, Model model, HttpServletRequest request) {

        User u = userService.login(user);
        Map<String, Object> map = new HashMap<>();

        if (u != null) {
            //成功
            boolean data = true;
            model.addAttribute("data", data);
            HttpSession session = request.getSession();
            session.setAttribute("user", u);
            return data;
        } else {
            //失败
            return false;
        }
    }

    @RequestMapping("/register")
    @ResponseBody
    public boolean register(User user) {
        user.setIcon("/img/peiqi.jpg");
        boolean canRegister = userService.canRegister(user);
        if (canRegister) {
            userDao.register(user);
            //注册成功
            return true;
        } else {
            return false;
        }
    }
}
